package com.jinzhi.jzapi.certificate.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.certificate.pojo.CombinedVo;
import com.jinzhi.jzapi.certificate.pojo.ConsultationsVo;
import com.jinzhi.jzweb.dao.ArchivesDao;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.DaysUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/jzApi/index")
public class ApiIndexController extends BaseController{
    @Autowired
    private DictService dictService;
    @Autowired
    private UserService userService;
    @Autowired
    private ConsultationsService consultationsService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private   BookOrderService bookOrderService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private ArchivesDao archivesDao;
    @Autowired
    private ExamRegistrationService examRegistrationService;
    /**
     * localhost:8877//jzApi/index/archivesInsert
     * 简历学校档案信息表
     * @return
     */

    /**
     *
     * @description: 培训信息详情
     * @author: YangQiWu
     * @date: 2023/3/31 11:01
     * @param: [id, model]
     * @return: java.lang.String
     **/
    @Log("培训详情页面")
    @GetMapping("/infoExamRegistration1/{id}")
    String infoExamRegistration1(@PathVariable("id") Long id, Model model) {
        ExamRegistrationDO examRegistrationDO = examRegistrationService.selectById(id);
        if (examRegistrationDO.getExamType().equals("0")){
            examRegistrationDO.setExamType("1+X幼儿照护职业技能等级证书师资及考评员");
        }
        if (examRegistrationDO.getExamType().equals("1")){
            examRegistrationDO.setExamType("1+X幼儿照护职业技能等级证书高级师资及考评员");
        }
        if (examRegistrationDO.getExamType().equals("2")){
            examRegistrationDO.setExamType("1+X幼儿照护职业技能等级证书考评员到期复审换证");
        }
        if (examRegistrationDO.getExamType().equals("3")){
            examRegistrationDO.setExamType("1+X产后恢复职业技能等级证书师资及考评员");
        }
        if (examRegistrationDO.getExamType().equals("4")){
            examRegistrationDO.setExamType("1+X幼儿照护、产后恢复职业技能等级证书考务技术与督导员");
        }
        if (examRegistrationDO.getExamType().equals("5")){
            examRegistrationDO.setExamType("高职护理——江西国培");
        }
        if (examRegistrationDO.getExamType().equals("6")){
            examRegistrationDO.setExamType("中职幼儿保育——江西国培");
        }
        if (examRegistrationDO.getExamType().equals("7")){
            examRegistrationDO.setExamType("教学能力竞赛研修班");
        }
        if (examRegistrationDO.getExamType().equals("8")){
            examRegistrationDO.setExamType("金砖大赛 - 第二届婴幼儿照护训练营");
        }
        if (examRegistrationDO.getExamType().equals("9")){
            examRegistrationDO.setExamType("金砖大赛-首届产后恢复训练营");
        }
        if (examRegistrationDO.getExamType().equals("10")){
            examRegistrationDO.setExamType("2024年国培省培班");
        }
        if (examRegistrationDO.getExamType().equals("11")){
            examRegistrationDO.setExamType("会议");
        }
        if (examRegistrationDO.getExamType().equals("12")){
            examRegistrationDO.setExamType("1+X幼儿照护、产后恢复职业技能等级证书考务技术员与督导员到期复审换证");
        }
        if (examRegistrationDO.getExamType().equals("13")){
            examRegistrationDO.setExamType("1+X产后恢复职业技能等级证书考评员到期复审换证");
        }
        if (examRegistrationDO.getExamType().equals("14")){
            examRegistrationDO.setExamType("金砖大赛-第二届产后恢复训练");
        }
        if (examRegistrationDO.getExamType().equals("15")){
            examRegistrationDO.setExamType("金砖大赛-第三届婴幼儿照护训练营");
        }
        if (examRegistrationDO.getExamType().equals("16")){
            examRegistrationDO.setExamType("金砖大赛-首届老年人能力评估训练营");
        }
        examRegistrationDO.setRegistrationStartDate(DateTime.of(examRegistrationDO.getRegistrationStartDate()));
        examRegistrationDO.setRegistrationEndDate(DateTime.of(examRegistrationDO.getRegistrationEndDate()));
        examRegistrationDO.setClassMeetingDate(DateTime.of(examRegistrationDO.getClassMeetingDate()));
        examRegistrationDO.setTrainingStartDate(DateTime.of(examRegistrationDO.getTrainingStartDate()));
        examRegistrationDO.setTrainingEndDate(DateTime.of(examRegistrationDO.getTrainingEndDate()));
        examRegistrationDO.setGraduationDate(DateTime.of(examRegistrationDO.getGraduationDate()));

        List<String> trainingPdfList = new ArrayList<>();
        List<String> fileNameList = new ArrayList<>();
        List<JSONObject> list = new ArrayList<>();
        if(examRegistrationDO.getTrainingPdf() != null && examRegistrationDO.getFileName() != null){
            trainingPdfList = Arrays.asList(examRegistrationDO.getTrainingPdf().split(","));
            fileNameList = Arrays.asList(examRegistrationDO.getFileName().split(","));
            for(int i=0;i<fileNameList.size();i++){
                Map map = new HashMap();
                map.put("trainingPdf",trainingPdfList.get(i));
                map.put("fileName",fileNameList.get(i));
                JSONObject jsonObject = new JSONObject(map);
                list.add(jsonObject);
            }
        }

        model.addAttribute("list",list);
        model.addAttribute("examRegistrationDO", examRegistrationDO);
        return "certificateWeb/tradeInfo/applicationDetail";
    }

    @Log("查询考试报名相关信息")
    @ResponseBody
    @GetMapping("/listExamRegistration1")
    public Result<Page<ExamRegistrationDO>> listExamRegistration1(ExamRegistrationDO examRegistrationDO){
        Wrapper<ExamRegistrationDO> wrapper = new EntityWrapper<ExamRegistrationDO>().orderBy("id", false);
        if (StringUtil.notEmpty(examRegistrationDO.getExamType())) {
            wrapper.eq("exam_type", examRegistrationDO.getExamType());
        }
        if (StringUtil.notEmpty(examRegistrationDO.getNoticeTitle())) {
            wrapper.like("notice_title", examRegistrationDO.getNoticeTitle());
        }
        wrapper.orderBy("publish_date",false);

        // 查询列表数据
        Page<ExamRegistrationDO> page = examRegistrationService.selectPage(getPage(ExamRegistrationDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ExamRegistrationDO obj = (ExamRegistrationDO) page.getRecords().get(i);
            if (obj.getExamType().equals("0")){
                obj.setExamType("1+X幼儿照护职业技能等级证书师资及考评员");
            }
            if (obj.getExamType().equals("1")){
                obj.setExamType("1+X幼儿照护职业技能等级证书高级师资及考评员");
            }
            if (obj.getExamType().equals("2")){
                obj.setExamType("1+X幼儿照护职业技能等级证书考评员到期复审换证");
            }
            if (obj.getExamType().equals("3")){
                obj.setExamType("1+X产后恢复职业技能等级证书师资及考评员");
            }
            if (obj.getExamType().equals("4")){
                obj.setExamType("1+X幼儿照护、产后恢复职业技能等级证书考务技术与督导员");
            }
            if (obj.getExamType().equals("5")){
                obj.setExamType("高职护理——江西国培");
            }
            if (obj.getExamType().equals("6")){
                obj.setExamType("中职幼儿保育——江西国培");
            }
            if (obj.getExamType().equals("7")){
                obj.setExamType("教学能力竞赛研修班");
            }
            if (obj.getExamType().equals("8")){
                obj.setExamType("金砖大赛 - 第二届婴幼儿照护训练营");
            }
            if (obj.getExamType().equals("9")){
                obj.setExamType("金砖大赛-首届产后恢复训练营");
            }
            if (obj.getExamType().equals("10")){
                obj.setExamType("2024年国培省培班");
            }
            if (obj.getExamType().equals("11")){
                obj.setExamType("会议");
            }
            if (obj.getExamType().equals("12")){
                obj.setExamType("1+X幼儿照护、产后恢复职业技能等级证书考务技术员与督导员到期复审换证");
            }
            if (obj.getExamType().equals("13")){
                obj.setExamType("1+X产后恢复职业技能等级证书考评员到期复审换证");
            }
            if (obj.getExamType().equals("14")){
                obj.setExamType("金砖大赛-第二届产后恢复训练营");
            }
            if (obj.getExamType().equals("15")){
                obj.setExamType("金砖大赛-第三届婴幼儿照护训练营");
            }
            if (obj.getExamType().equals("16")){
                obj.setExamType("金砖大赛-首届老年人能力评估训练营");
            }
            UserDO userDO = userService.selectById(obj.getUserId());
            obj.setUserName(userService.selectById(obj.getUserId()).getUsername());
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }
    @GetMapping("/archivesInsert")
    public Object archivesInsert()throws Exception{

        List<Map> list=archivesService.sumMoneySchool();

        for(Map li:list){
            Map map1 =new HashMap();
            map1.put("name",li.get("orgName"));
            List list1=  archivesService.listArchives(map1);
            if(list1.size()==0){
                ArchivesDO archivesDO=new ArchivesDO();
                archivesDO.setSchoolName(li.get("orgName").toString());
                archivesDO.setUpdateTime(new Date());
                archivesDO.setDepartment(li.get("region_department").toString());
                archivesDO.setPerson(li.get("regionUserId").toString());
                archivesDO.setProvince(li.get("province").toString());
                archivesDO.setNumber(li.get("mobile").toString());
                //考试学生总人数
                archivesDO.setStudentNum(Integer.valueOf(li.get("stuNum").toString()) );
                //应收款
                archivesDO.setMoney((BigDecimal) li.get("receivables"));
                //支出 返款加上劳务费
                archivesDO.setExpenditure( DaysUtil.ToBigDecimal(li.get("returnMoney")).add(DaysUtil.ToBigDecimal(li.get("laborWage")))  );
                //实际总收款
                archivesDO.setActualMoney((BigDecimal) li.get("received"));
                archivesDO.setReturnMoney(DaysUtil.ToBigDecimal(li.get("returnMoney")));
                //劳务费支出
                archivesDO.setLaborWage(DaysUtil.ToBigDecimal(li.get("laborWage")));
                archivesService.insert(archivesDO);
            }
            //学校名称查询所有订单总金额 其他订单总金额  学生人数  老师人数   业务员姓名  电话   部门  支出

          Map mapSchoot=  bookOrderService.orderSchool(li.get("orgName").toString());
            if(mapSchoot!=null){
              String mapschid=  archivesService.schoolNmae(li.get("orgName").toString());
              if(mapschid!=null){
                  ArchivesDO archivesDO=archivesService.selectById(mapschid);
                  //订单总价格
                  archivesDO.setOrderTotal(   DaysUtil.ToBigDecimal(mapSchoot.get("order_money")));
                  //实际订单收款
                  archivesDO.setOrderTotalMoney(DaysUtil.ToBigDecimal(mapSchoot.get("actual_money")));
                  //负责人
                  Map map=   archivesDao.countTeacher(li.get("orgName").toString());
                  if(map==null){
                      archivesDO.setTeacherNum(0);
                  }else {
                      archivesDO.setTeacherNum(Integer.valueOf(map.get("count").toString()));
                  }
                  archivesService.updateById(archivesDO);
              }
            }
            //其他订单统计
            Map mapSchootnew=   bookOrderService.orderSchoolnew(li.get("orgName").toString());
            if(mapSchootnew!=null){
                String mapschid=  archivesService.schoolNmae(li.get("orgName").toString());
                if(mapschid!=null){
                    ArchivesDO archivesDO=archivesService.selectById(mapschid);
                    //订单总价格
                    archivesDO.setOtherOrderTotal(   DaysUtil.ToBigDecimal(mapSchootnew.get("order_money")));
                    //负责人
                    Map map=   archivesDao.countTeacher(li.get("orgName").toString());
                    if(map==null){
                        archivesDO.setTeacherNum(0);
                    }else {
                        archivesDO.setTeacherNum(Integer.valueOf(map.get("count").toString()));
                    }
                    archivesService.updateById(archivesDO);
                }
            }
        }
        List<Map> listOrg=   archivesService.listOrg();
        for(Map li:listOrg){
            if(li.get("province")!=null){
                Map map1 =new HashMap();
                map1.put("name",li.get("orgName"));
                List list1=  archivesService.listArchives(map1);
                if(list1.size()==0){
                    ArchivesDO archivesDO=new ArchivesDO();
                    archivesDO.setSchoolName(li.get("orgName").toString());
                    archivesDO.setUpdateTime(new Date());
                    archivesDO.setProvince(li.get("province").toString());
                    archivesService.insert(archivesDO);
                }
            }
        }
        return Result.ok();
    }


    /**
     * api小程序端-banner图信息接口--公开方法，不需要登录
     *
     * @Description: 首页banner信息查询
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selBanners")
    @Log("api小程序端-banner图信息接口")
    @ApiOperation(value = "api小程序端-banner图信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selBanners() {
        Map<String, String> map = new HashMap<>();
        map.put("name", "证书小程序banner图");
        map.put("type", "cer_banners");
        List<Map> jsonArray = (List<Map>) EhCacheUtil.get("selBanners11");

        if(jsonArray==null){
            List<Map> maps = dictService.selTypeNameVue(map);
            EhCacheUtil.put("selBanners11" , maps);
            return ApiResult.success(maps);
        }else {
            return ApiResult.success(jsonArray);
        }
    }

    /**
     * api小程序端-信息列表接口--公开方法，不需要登录
     *
     * @Description: 证书信息列表查询，参数：页码，显示数，栏目名称（筛选条件）
     * @Param: [current, number, columnName]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selNewsList")
    @Log("api小程序端-信息列表接口")
    @ApiOperation(value = "api小程序端-信息列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selNewsList(String current, String number,String firstColumn,String columnName) {
        Page<ConsultationsVo> page = consultationsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number),firstColumn, columnName);
        return ApiResult.success(page);
    }

    /**
     * api小程序端-新信息列表接口--公开方法，不需要登录
     *
     * @Description: 证书信息列表查询，参数：页码，显示数，栏目名称（筛选条件）
     * @Param: [current, number, columnName]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selNewsList1")
    @Log("api小程序端-信息列表接口")
    @ApiOperation(value = "api小程序端-信息列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selNewsList1(String current, String number,String firstColumn,String columnName) {
        Page<CombinedVo> page = consultationsService.selNewsList1(Integer.parseInt(current), Integer.parseInt(number),firstColumn, columnName);
        return ApiResult.success(page);
    }
    
    /**
     * api小程序端-信息列表接口--公开方法，不需要登录
     *
     * @Description: 证书信息列表查询，参数：页码，显示数，栏目名称（筛选条件）
     * @Param: [current, number, columnName]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selDataList")
    @Log("api小程序端-信息列表接口")
    @ApiOperation(value = "api小程序端-信息列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selDataList(@RequestHeader(value = TOKEN_TAG, required = false) String token,String current, String number,String firstColumn,String columnName) {
    	
    	UserDO user = this.getClientUser(token);
    	if (user == null){
            return ApiResult.invalid();
        }
        Page<ConsultationsVo> page = consultationsService.selectListByUserIdPage(Integer.parseInt(current), Integer.parseInt(number),firstColumn, columnName,user.getId());
        
        return ApiResult.success(page);
    }

    /**
     * api小程序端-信息含有缩略图列表接口--公开方法，不需要登录
     *
     * @Description: 缩略图信息查询，参数：页码，显示数，一级栏目，栏目名称（筛选条件）
     * @Param: [current, number, firstColumn，columnName]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selNewsThumbnailList")
    @Log("信息含有缩略图列表接口")
    @ApiOperation(value = "api小程序端-信息含有缩略图列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selNewsThumbnailList(String current, String number,String firstColumn,String columnName) {
        Page<ConsultationsVo> page = consultationsService.selectThumbnailListPage(Integer.parseInt(current), Integer.parseInt(number),firstColumn, columnName);
        return ApiResult.success(page);
    }

    /**
     * api小程序端-信息详情接口--公开方法，不需要登录
     *
     * @Description: 证书信息详情查询，参数：证书信息id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selNewsDetail")
    @Log("api小程序端-信息详情接口")
    @ApiOperation(value = "api小程序端-信息详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selNewsDetail(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("id");
        }

        Map map = new HashMap();
        ConsultationsDO consultationsDO = consultationsService.selectById(id);
        if (consultationsDO != null) {
            map.put("id", consultationsDO.getId());
            map.put("title", consultationsDO.getTitle());//信息标题
            map.put("files", consultationsDO.getFiles());//附件
            map.put("content", consultationsDO.getContents());//内容
            map.put("createrDate", consultationsDO.getCreaterDate());//发布时间
            map.put("accessNumber", consultationsDO.getAccessNumber());//访问次数
            UserDO userDO = userService.getByUserId(consultationsDO.getCreaterId());
            if (userDO != null) {
                map.put("createrName", userDO.getUsername());
            } else {
                map.put("createrName", "系统管理员");
            }

            //添加查询次数
            Long queries = consultationsDO.getAccessNumber();
            queries = queries + 1;
            consultationsDO.setAccessNumber(queries);
            consultationsService.updateById(consultationsDO);
        }
        return ApiResult.success(map);
    }


    /**
     * api小程序端-证书列表接口--公开方法，不需要登录
     *
     * @Description: 证书信息列表查询，参数：页码，显示数
     * @Param: [current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selCertificateList")
    @Log("api小程序端-证书列表接口")
    @ApiOperation(value = "api小程序端-证书列表接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCertificateList(String current, String number) {
        Page<Map<String, Object>> page = certificateNewsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number));
        return ApiResult.success(page);
    }


    /**
     * api小程序端-证书详情接口--公开方法，不需要登录
     *
     * @Description: 查询证书详情信息，参数：x证书id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selCertificateDetail")
    @Log("api小程序端-证书详情接口")
    @ApiOperation(value = "api小程序端-证书详情接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selCertificateDetail(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.lack("id");
        }

        Map map = new HashMap();
        CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(id);
        if (certificateNewsDO != null) {
            map.put("id", certificateNewsDO.getId());
            map.put("grade", certificateNewsDO.getGrade());//证书等级
            map.put("relatedMajors", certificateNewsDO.getRelatedMajors());//相关专业
            map.put("examFee", certificateNewsDO.getExamFee());//考试总费用
            map.put("createrDate", certificateNewsDO.getCreaterDate());//发布时间
            map.put("introduce", certificateNewsDO.getIntroduce());//介绍
            CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(certificateNewsDO.getProfileId());
            if (certificateProfileDO != null) {
                map.put("name", certificateProfileDO.getName());//证书名称
                map.put("organization", certificateProfileDO.getOrganization());//发证机构
            } else {
                map.put("name", "");//证书名称
                map.put("organization", "");//发证机构
            }
        }
        return ApiResult.success(map);
    }
}
